package com.uduew.sjd.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.os.SystemClock
import android.provider.MediaStore
import android.provider.Settings
import android.telephony.TelephonyManager
import com.uduew.utils.NetworkUtils
import java.io.File

object SystemInfoCollector {
    // 是否root
    fun isRooted(): Boolean {
        return checkRootMethod1() || checkRootMethod2()
    }

    private fun checkRootMethod1(): Boolean {
        val paths = arrayOf(
            "/system/bin/su",
            "/system/xbin/su",
            "/sbin/su",
            "/data/local/xbin/su"
        )
        return paths.any { File(it).exists() }
    }

    private fun checkRootMethod2(): Boolean {
        return try {
            Runtime.getRuntime().exec("su")
            true
        } catch (e: Exception) {
            false
        }
    }

    // 是否VPN连接
    fun isVpnActive(): Boolean {
        return NetworkUtils.isUsingVPN()
    }

    // 手机运行时间（单位：毫秒）
    fun getUptimeMillis(): Long {
        return SystemClock.elapsedRealtime()
    }

    // 键盘类型
    fun getKeyboardType(context: Context): String {
        return Settings.Secure.getString(
            context.contentResolver,
            Settings.Secure.DEFAULT_INPUT_METHOD
        ) ?: "unknown"
    }

    // 是否是模拟器
    fun isEmulator(): Boolean {
        return (Build.FINGERPRINT.startsWith("generic")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MANUFACTURER.contains("Genymotion"))
    }

    // 是否启用调试模式
    fun isDebugMode(context: Context): Boolean {
        return Settings.Global.getInt(
            context.contentResolver,
            Settings.Global.ADB_ENABLED, 0
        ) != 0
    }

    // 手机信号强度（需要权限）
    fun getSignalStrength(context: Context): String {
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            when (tm.signalStrength?.level) {
                0 -> "NONE"
                1 -> "POOR"
                2 -> "MODERATE"
                3 -> "GOOD"
                4 -> "GREAT"
                else -> "UNKNOWN"
            }
        } else {
            "UNKNOWN"
        }
    }

    // 手机照片数量（需要权限）
    fun getPhotoCount(context: Context): Int {
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Images.Media._ID)
        return context.contentResolver.query(
            uri,
            projection,
            null,
            null,
            null
        )?.use { cursor -> cursor.count } ?: 0
    }

    // 屏幕尺寸和密度
    data class ScreenInfo(
        val width: Int,
        val height: Int,
        val density: Float,
        val dpi: Int
    )

    fun getScreenInfo(context: Context): ScreenInfo {
        val metrics = context.resources.displayMetrics
        return ScreenInfo(
            width = metrics.widthPixels,
            height = metrics.heightPixels,
            density = metrics.density,
            dpi = metrics.densityDpi
        )
    }

    // CPU核数
    fun getCpuCoreCount(): Int {
        return Runtime.getRuntime().availableProcessors()
    }

    // 内存信息（单位：MB）
    data class MemoryUsage(
        val free: Double,
        val total: Double,
        val max: Double
    )

    fun getMemoryInfo(context: Context): MemoryUsage {
        val memInfo = ActivityManager.MemoryInfo()
        (context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(
            memInfo
        )

        return MemoryUsage(
            free = memInfo.availMem.toDouble() / 1024 / 1024,
            total = memInfo.totalMem.toDouble() / 1024 / 1024,
            max = (ActivityManager.MemoryInfo().totalMem * 0.85) / 1024 / 1024
        )
    }

    // 电量信息
    data class BatteryInfo(
        val maxCapacity: Int,
        val currentLevel: Int
    )

    fun getBatteryInfo(context: Context): BatteryInfo {
        val batteryStatus = context.registerReceiver(
            null,
            IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        )

        return BatteryInfo(
            maxCapacity = batteryStatus?.getIntExtra(
                BatteryManager.EXTRA_SCALE,
                -1
            ) ?: 100,
            currentLevel = batteryStatus?.getIntExtra(
                BatteryManager.EXTRA_LEVEL,
                -1
            ) ?: 0
        )
    }
}
